<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>pdf</title>

    <script src="src/vue.js"></script>
    <script src="src/pdf.js"></script>
    <script src="src/pdf.worker.js"></script>
    <script src="src/fabric.js"></script>
    <script src="src/axios.min.js"></script>
    <style>
        .elesign {
            text-align:center;
        }
        #ele-canvas {
            border: 1px solid #5ea6ef;
        }
        .ele-control {
            margin-top: 30px;
        }
        #page-input {
            width: 7%;
        }
    </style>
</head>
<body>
    <div class="elesign" id="app">
        <!-- pdf的预览 -->
        <div class="center">
            <div>
              <button @click="prevPage">上一页</button>
              <button @click="nextPage">下一页</button>
              <input id="page-input" v-model:number="pageNum" type="number" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" />
              <button>{{ pageNum }}/<span id="page_count"></span>页</button>
            </div>
            <canvas id="the-canvas" />
        </div>
      
        <!-- 盖章部分 -->
        <canvas id="ele-canvas"></canvas>
        
        <div class="ele-control">
            <button @click="addSeal()">添加公章</button>
            <button @click="addSign()">添加签名</button>
            <button @click="removeSignature">删除签章</button >
            <button @click="confirmSignature">确定当前签章位置</button>
            <button @click="clearSignature">清除所有签章</button>
            <button @click="submitSignature">提交所有签章信息</button>
        </div>
        <!-- <img src="../assets/logo.png" id="img" style="display:none" /> -->
    </div>
   
</body>
</html>

<script>
    let pdfjsLib = window["pdfjs-dist/build/pdf"];

    pdfjsLib.GlobalWorkerOptions.workerSrc = `http://${window.location.host}/pdf.worker.js`;

    let storage = window.localStorage;

    var app = new Vue ({
        el: '#app',
        data() {
            return {
                pdfUrl: '',
                pdfDoc: null,
                pageNum: 1,
                scale: 1,
                pageRendering: false,
                pageNumPending: null,
                sealUrl: '',
                signUrl: '',
                canvas: null,
                ctx: null,
                canvasEle: null,
                whDatas: null
            };
        },

        //计算属性,就是依赖其它的属性计算所得出最后的值
        computed: {
            hasSigna() {
                return !!this.canvasEle && !!this.canvasEle.getObjects()[0] ? true : false;
            },
        },

        //监听一个值的变化,然后执行相对应的函数。
        watch: {
            whDatas: {
                handler() {
                    if (!!this.whDatas) {
                        this.renderFabric();
                        this.canvasEvents();
                    }
                },
            },

            pdfUrl: function(val){
                this.$nextTick(() => {
                   this.showpdf(val);
                });
            },
            pageNum: function(pageNum) {
                pageNum = Number(pageNum);
                if (pageNum < 1) {
                    this.pageNum = 1;
                    return;
                }
                if(pageNum > this.pdfDoc.numPages) {
                    this.pageNum = this.pdfDoc.numPages;
                }
                if(!(/(^[1-9]\d*$)/.test(pageNum))) {
                   this.pageNum = 1;
                   return;
                }
                this.commonSign(pageNum);
                this.queueRenderPage(pageNum);
            }
        },

        //事件方法
        methods: {
            renderPage(num) {
                let _this = this;
                this.pageRendering = true;
                // Using promise to fetch the page
                return this.pdfDoc.getPage(num).then((page) => {
                    let viewport = page.getViewport({ scale: _this.scale });
                    _this.canvas.height = viewport.height;
                    _this.canvas.width = viewport.width;
            
                    // Render PDF page into canvas context
                    let renderContext = {
                        canvasContext: _this.ctx,
                        viewport: viewport,
                    };
                    let renderTask = page.render(renderContext);
            
                    // Wait for rendering to finish
                    renderTask.promise.then(() => {
                        _this.pageRendering = false;
                        if (_this.pageNumPending !== null) {
                        // New page rendering is pending
                        this.renderPage(_this.pageNumPending);
                        _this.pageNumPending = null;
                        }
                    });
                });
            },
            queueRenderPage(num) {
                if (this.pageRendering) {
                    this.pageNumPending = num;
                } else {
                    this.renderPage(num);
                }
            },
            prevPage() {

                if (this.pageNum <= 1) {
                    return;
                }
                this.pageNum--;
            },
            nextPage() {
                if (this.pageNum >= this.pdfDoc.numPages) {
                    return;
                }
                this.pageNum++;
            },
            showpdf(pdfUrl) {
                this.canvas = document.getElementById("the-canvas");
                this.ctx = this.canvas.getContext("2d");
        
                pdfjsLib.getDocument(pdfUrl).promise.then((pdfDoc_) => {
                    this.pdfDoc = pdfDoc_;
                    document.getElementById("page_count").textContent = this.pdfDoc.numPages;
                    this.renderPage(this.pageNum).then((res) => {
                        this.renderPdf({
                            width: this.canvas.width,
                            height: this.canvas.height,
                        });
                    });
                    this.commonSign(this.pageNum, true);
                });
            },

            /**
             *  盖章部分开始
            */
            // 设置绘图区域宽高
            renderPdf(data) {
                this.whDatas = data;
                // console.log(data)
                document.querySelector(".elesign").style.width = data.width + "px";
            },

            // 生成绘图区域
            renderFabric() {
                let canvaEle = document.querySelector("#ele-canvas");

                canvaEle.width = this.whDatas.width;
                canvaEle.height = this.whDatas.height;

                this.canvasEle = new fabric.Canvas(canvaEle);
                let container = document.querySelector(".canvas-container");
                container.style.position = "absolute";
                container.style.top = "42px";
            },

            // 相关事件操作哟
            canvasEvents() {
                // 拖拽边界 不能将图片拖拽到绘图区域外
                this.canvasEle.on("object:moving", function (e) {
                    var obj = e.target;
                    // if object is too big ignore
                    if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
                        return;
                    }
                    obj.setCoords();        
                    // top-left  corner
                    if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0){
                        obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
                        obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
                    }
                    // bot-right corner
                    if(obj.getBoundingRect().top+obj.getBoundingRect().height  > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width  > obj.canvas.width){
                        obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
                        obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
                    }
                });
            },

            // 添加公章
            addSeal(sealUrl = this.sealUrl, left = this.whDatas.width / 3, top = this.whDatas.height - 165) {
                fabric.Image.fromURL(
                    sealUrl,
                    (oImg) => {
                        oImg.set({
                            left: left,
                            top: top,
                            width: 165,
                            height: 165,
                            // angle: 10,
                            scaleX: 0.6,
                            scaleY: 0.6,
                        });
                        // oImg.scale(0.5); //图片缩小一半
                        this.canvasEle.add(oImg);
                    }
                );
            },

            //添加签名
            addSign(signUrl = this.signUrl, left = this.whDatas.width / 2, top = this.whDatas.height - 70) {
                fabric.Image.fromURL(
                    signUrl,
                    (oImg) => {
                        oImg.set({
                            left: left,
                            top: top,
                            width: 165,
                            height: 70,
                            // angle: 10,
                            scaleX: 0.6,
                            scaleY: 0.6,
                        });
                        // oImg.scale(0.5); //图片缩小一半
                        this.canvasEle.add(oImg);
                    }
                );
            },

            // 删除签章
            removeSignature() {
                this.canvasEle.remove(this.canvasEle.getActiveObject())
                // this.canvasEle.remove(this.canvasEle.getObjects()[0]);
            },

            //翻页展示盖章信息
            commonSign(pageNum, isFirst = false) {
                if(isFirst == false) this.canvasEle.remove(this.canvasEle.clear()); //清空页面所有签章
                let caches = JSON.parse(storage.getItem('signs')); //获取缓存字符串后转换为对象
                if(caches == null) return false;
                let datas = caches[this.pageNum];
                if(datas != null && datas != undefined) {
                    for (let index in datas) {
                        if(datas[index].width == datas[index].height) {
                            this.addSeal(datas[index].sealUrl, datas[index].left, datas[index].top);
                        } else {
                            this.addSign(datas[index].sealUrl, datas[index].left, datas[index].top);
                        }
                    }
                }
            },

            //确认签章位置并保存到缓存
            confirmSignature() {
                let data = this.canvasEle.getObjects(); //获取当前页面内的所有签章信息
                let caches = JSON.parse(storage.getItem('signs')); //获取缓存字符串后转换为对象

                let signDatas = {}; //存储当前页的所有签章信息
                let i = 0;
                let sealUrl = '';
                for(var val of data) {
                    if(val.width == val.height) {
                        sealUrl = this.sealUrl;
                    } else {
                        sealUrl = this.signUrl;
                    }
                    signDatas[i] =  {
                        width: val.width,
                        height: val.height,
                        top: val.top,
                        left: val.left,
                        angle: val.angle,
                        translateX: val.translateX,
                        translateY: val.translateY,
                        scaleX: val.scaleX,
                        scaleY: val.scaleY,
                        pageNum: this.pageNum,
                        sealUrl: sealUrl,
                    }
                    i++;
                }
                if(caches == null) {
                    caches = {};
                    caches[this.pageNum] = signDatas;   
                } else {
                    caches[this.pageNum] = signDatas;
                }
                storage.setItem('signs', JSON.stringify(caches)); //对象转字符串后存储到缓存
            },

            //提交数据
            submitSignature() {
                let caches = storage.getItem('signs');
                let param = '&pdfWidth='+this.whDatas.width+'&pdfHeight='+this.whDatas.height+'&signs='+caches;
                axios.post('/index.php?v=getInfo'+param)
                .then(function (response) {
                    if(response.data.code == 200) {
                        // storage.removeItem('signs');
                    }
                })
                .catch(function (error) {
                    console.log(error);
                }); 
            },

            //清空数据
            clearSignature() {
                this.canvasEle.remove(this.canvasEle.clear()); //清空页面所有签章
                storage.removeItem('signs'); //清除缓存
            }
            /**
             *  盖章部分结束
            */
        },

        //未渲染html页面时执行
        created: function () {
            var that = this;
            that.sealUrl = `http://${window.location.host}/`+'seal.png';
            that.signUrl = `http://${window.location.host}/`+'sign.png';
            that.pdfUrl = './show.pdf';

            // //获取pdf路径和签章路径
            // let param = "&id=11";
            // axios.get('/index.php?v=infos'+param)
            // .then(function (response) {
            //     if(response.data.code == 200) {
            //         that.sealUrl = `http://${window.location.host}/`+response.data.data.seal;
            //         that.signUrl = `http://${window.location.host}/`+response.data.data.sign;
            //         that.pdfUrl = response.data.data.pdf;
            //     }
            // })
            // .catch(function (error) {
            //     console.log(error);
            // });
        },

        //html加载完成后执行
        mounted() {
     
        },
    });

</script>